package com.zml.control;

import com.huawei.ailifeability.netconfig.api.NetConfigApi;
import com.huawei.ailifeability.netconfig.model.CommonInfo;
import com.zml.control.database.PreferenceDataBase;
import com.zml.control.okhttp.HuaweiCloudApi;
import com.zml.control.widget.controller.*;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.ProviderFormInfo;
import ohos.aafwk.content.Intent;
import ohos.ace.ability.AceAbility;
import ohos.app.Context;
import ohos.data.DatabaseHelper;
import ohos.data.preferences.Preferences;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.utils.zson.ZSONObject;

import java.io.IOException;

/**
 * Device control ability.
 * Obtain the productId, productName and sessionId from the intent and determine the control page of the device
 * based on the productName.
 */
public class ControlMainAbility extends AceAbility {
    private static final HiLogLabel TAG = new HiLogLabel(HiLog.DEBUG, 0x0, ControlMainAbility.class.getName());
    public static final int DEFAULT_DIMENSION_2X2 = 2;
    public static final int DIMENSION_1X2 = 1;
    public static final int DIMENSION_2X4 = 3;
    public static final int DIMENSION_4X4 = 4;
    private static final String START_PARAMS = "__startParams";
    private static final String SESSION_ID = "session_id";
    private static final String FA_DEVICE_ID = "device_id";
    private static final String FA_DEVICE_PRODUCT_ID = "product_id";
    private static final String FA_DEVICE_PRODUCT_NAME = "product_name";
    private static final int INVALID_FORM_ID = -1;
    private boolean goToFullScreen = false;
    private String topWidgetSlice;
    private Context context;


    @Override
    public void onStart(Intent intent) {
        if (goToFullScreen) {
            DataHandlerAbility.setIsFullScreen(true);
            DataHandlerAbility.setAbilityContext(this);
            super.onStart(intent);
            goToFullScreen = false;
            return;
        }
        String sessionId = null;
        String productName = "SOLAR";
        if (intent.getParams().keySet().contains(START_PARAMS)) {
            ZSONObject zsonObject = ZSONObject.stringToZSON((String) intent.getParams().getParam(START_PARAMS));
            sessionId = zsonObject.getString(SESSION_ID);
            productName = zsonObject.getString(FA_DEVICE_PRODUCT_NAME);
        }
        intent.setParam("window_modal", 1);

        String deviceId = intent.getStringParam(FA_DEVICE_ID);
        NetworkDeviceDataHandler.setSessionId(sessionId);
        DataHandlerAbility.register(this, deviceId, productName);
        DataHandlerAbility.setIsFullScreen(false);
        super.onStart(intent);
        if (intentFromWidget(intent)) {
            topWidgetSlice = getRoutePageSlice(intent);
            if (topWidgetSlice != null) {
                setMainRoute(topWidgetSlice);
            }
        }
        /************************ 程序启动获取Token ***************************/

        try {
            HuaweiCloudApi.getIAMUserToken(this);
        } catch (IOException e) {
            e.printStackTrace();
        }

//        try {
//            HiLog.info(TAG, "ZML"+"00000000000000000000");
//            PreferenceDataBase.SaveIAMUserToken(this);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        try {
//            HiLog.info(TAG, "ZML"+"111111111111111111");
//            HiLog.info(TAG, "onTriggerFormEvent: " + PreferenceDataBase.GetIAMUserToken(this));
//        } catch (IOException e) {
//            e.printStackTrace();
//        }

    }

    @Override
    public void onNewIntent(Intent intent) {
        if (intent.getParams().keySet().contains(START_PARAMS)) {
            ZSONObject zsonObject = ZSONObject.stringToZSON((String) intent.getParams().getParam(START_PARAMS));
            goToFullScreen = zsonObject.getBoolean("fullScreen");
            if (goToFullScreen) {
                restart();
            }
        }
        super.onNewIntent(intent);
        if (intentFromWidget(intent)) {
            String newWidgetSlice = getRoutePageSlice(intent);
            if (topWidgetSlice == null || !topWidgetSlice.equals(newWidgetSlice)) {
                topWidgetSlice = newWidgetSlice;
                restart();
            }
        }
    }

    @Override
    public void onStop() {
        if (!goToFullScreen) {
            CommonInfo commonInfo = new CommonInfo();
            commonInfo.setSessionId(NetworkDeviceDataHandler.getSessionId());
            NetConfigApi.getInstance().disconnectDevice(commonInfo, (code, controlMessage, str) -> {
            });
            DataHandlerAbility.deregister();
            super.onStop();
        }
    }

    @Override
    protected ProviderFormInfo onCreateForm(Intent intent) {
        HiLog.info(TAG, "onCreateForm");
        long formId = intent.getLongParam(AbilitySlice.PARAM_FORM_IDENTITY_KEY, INVALID_FORM_ID);
        String formName = intent.getStringParam(AbilitySlice.PARAM_FORM_NAME_KEY);
        int dimension = intent.getIntParam(AbilitySlice.PARAM_FORM_DIMENSION_KEY, DEFAULT_DIMENSION_2X2);
        HiLog.info(TAG, "onCreateForm: formId=" + formId + ",formName=" + formName);
        FormControllerManager formControllerManager = FormControllerManager.getInstance(this);
        FormController formController = formControllerManager.getController(formId);
        formController = (formController == null) ? formControllerManager.createFormController(formId,
                formName, dimension) : formController;
        if (formController == null) {
            HiLog.error(TAG, "Get null controller. formId: " + formId + ", formName: " + formName);
            return null;
        }

        //初始化时先在线更新一下卡片
        onUpdateForm(formId);

        return formController.bindFormData(formId);
    }

    @Override
    protected void onUpdateForm(long formId) {
        HiLog.info(TAG, "onUpdateForm");
        super.onUpdateForm(formId);
        FormControllerManager formControllerManager = FormControllerManager.getInstance(this);
        FormController formController = formControllerManager.getController(formId);
        formController.onUpdateFormData(formId);
    }

    @Override
    protected void onDeleteForm(long formId) {
        HiLog.info(TAG, "onDeleteForm: formId=" + formId);
        super.onDeleteForm(formId);
        FormControllerManager formControllerManager = FormControllerManager.getInstance(this);
        FormController formController = formControllerManager.getController(formId);
        formController.onDeleteForm(formId);
        formControllerManager.deleteFormController(formId);
    }

    @Override
    protected void onTriggerFormEvent(long formId, String message) {
        HiLog.info(TAG, "onTriggerFormEvent: " + message);
        super.onTriggerFormEvent(formId, message);
        FormControllerManager formControllerManager = FormControllerManager.getInstance(this);
        FormController formController = formControllerManager.getController(formId);
        formController.onTriggerFormEvent(formId, message);
    }

    private boolean intentFromWidget(Intent intent) {
        long formId = intent.getLongParam(AbilitySlice.PARAM_FORM_IDENTITY_KEY, INVALID_FORM_ID);
        return formId != INVALID_FORM_ID;
    }

    private String getRoutePageSlice(Intent intent) {
        long formId = intent.getLongParam(AbilitySlice.PARAM_FORM_IDENTITY_KEY, INVALID_FORM_ID);
        if (formId == INVALID_FORM_ID) {
            return null;
        }
        FormControllerManager formControllerManager = FormControllerManager.getInstance(this);
        FormController formController = formControllerManager.getController(formId);
        if (formController == null) {
            return null;
        }
        Class<? extends AbilitySlice> clazz = formController.getRoutePageSlice(intent);
        if (clazz == null) {
            return null;
        }
        return clazz.getName();
    }
}
